package data.join.com.utils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/5/10.
 */
public class BaseThread extends Thread {
    public final static int TIME_WAIT = 60;
    private CountDownLatch mCountDownLatch;
    Object mLock = new Object();

    public class AwaitException extends RuntimeException {
        public AwaitException(String msg){
            super(msg);
        }
   }

    public  void await(int timeOut){
        if(BaseThread.this.getId() == Thread.currentThread().getId()) {

            synchronized (mLock) {
                mCountDownLatch = new CountDownLatch(1);
            }

            try {
                if(timeOut > 0)
                    mCountDownLatch.await(timeOut, TimeUnit.SECONDS);
                else
                    mCountDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (mLock) {
                mCountDownLatch = null;
            }
        }else{
            throw new AwaitException("BaseThread.await() must be called in own Thread");
        }
    }

    public void wakeUp(){
        synchronized (mLock) {
            if (mCountDownLatch != null && mCountDownLatch.getCount() > 0) {
                mCountDownLatch.countDown();
            }
        }
    }
}
